package com.jt.sp06zuul.filter;

import com.jt.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    /**
     * 设置过滤器的类型:pre,routing,post,error
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
//设置过滤器顺序号
    @Override
    public int filterOrder() {
        //前置过滤器有五个,第五个过滤器才获得serviceId,所以放最后
        return 6;
    }

    /**
     * 判断针对当前请求,是否要过滤当前代码
     * 调用商品,判断权限
     * 调用用户/提单,不判断权限
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获得一个请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取服务id
        String id = (String) currentContext.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equals(id);
    }

    /**
     * 过滤代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();

        //获取request对象
        HttpServletRequest request = currentContext.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        //如果token不存在
        if(StringUtils.isBlank(token)){
            //阻止调用
            currentContext.setSendZuulResponse(false);
            //返回响应
            String string = JsonResult.build().code(400).msg("未登录").data(null).toString();
            currentContext.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            currentContext.setResponseBody(string);

        }
        //zuul当前版本不起任何作用
        return null;
    }
}
